import TodoEvent from "./class/TodoEvent";
import { ITodoData } from "./types/typings";

; ((doc) => {
    const oInput: HTMLInputElement = doc.querySelector('.todo-input');
    const oBtn: HTMLButtonElement = doc.querySelector('.todo-btn');
    const oTodoList: HTMLElement = doc.querySelector('.todo-list');
    const todoData: ITodoData[] = [
        { id: 1, content: '123', completed: false },
        { id: 2, content: '456', completed: true },
        { id: 3, content: '789', completed: false }
    ];
    const todoEvent: TodoEvent = new TodoEvent(todoData, oTodoList);
    const init = (): void => {
        bindEvent();
        
    }
    function bindEvent(): void {
        oBtn.addEventListener('click', handleBtnClick, false);
        oTodoList.addEventListener('click', handleTodoListClick, false);

    }
    function handleBtnClick(): void {
        const val: string = oInput.value.trim();
        if (val.length) {
            const ret = todoEvent.addTodo(<ITodoData>{
                id: new Date().getTime(),
                content: val,
                completed: false
            });
            if (ret && ret === 1001) {
                alert('列表已存在!');
                return;
            }
        }
        oInput.value = '';
    }
    function handleTodoListClick(e: MouseEvent): void {
        const tar = e.target as HTMLElement,
            tagName = tar.tagName.toLowerCase();
        const id: number = parseInt(tar.dataset.id);
        switch (tagName) {
            case 'input':
                todoEvent.toggleCompleted(tar, id);
                break;
            case 'button':
                todoEvent.removeTodo(tar, id);
                break;
            default:
                break;
        }
    }
    init();
})(document);